package cn.mrlong.base.utils;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by ly343 on 2018/4/26.
 */
public class CallSystemFunctionUtils {

    //获取imei
//    public static String getIMEI(Context context) {
//        return ((TelephonyManager) context.getSystemService(
//                Context.TELEPHONY_SERVICE)).getDeviceId();
//    }
    //获取androidid
    public static String getAndroidId(Context context) {
        return Settings.Secure.getString(
                context.getContentResolver(),
                Settings.Secure.ANDROID_ID);
    }
    //    关闭软键盘
    public static void hideSoftInputView(Activity context) {
        InputMethodManager manager = ((InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE));
        if (context.getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (context.getCurrentFocus() != null)
                manager.hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
    //打开GPS设置
    public static void openGPSSetting(Activity activity) {
        // 转到手机设置界面，用户设置GPS
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        activity.startActivityForResult(intent, 0); // 设置完成后返回到原来的界面
    }
    //    显示键盘
    public static void showSoftInputView(Activity context,View v) {
        InputMethodManager manager = ((InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE));
        if (context.getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (context.getCurrentFocus() != null)
                manager.showSoftInput(v, InputMethodManager.SHOW_FORCED);
        }
    }

    //    根据键盘显示情况判断显示还是隐藏
    public static void showhide(Activity context) {
        InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    //获取当前sdk版本号
    public static int getVERSION(){
        return Build.VERSION.SDK_INT;
    }

    //    获取sdk路径
    public static String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED);   //判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString();
    }

    //   给拍照的图片取名字
    public String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'IMG'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".jpg";
    }

    /**
     * 根据uri，找到img的存储位置
     *
     * @param originalUri 目标uri
     * @return 存储位置（String）
     * @throws IOException
     */
    public static String getImgUrl(Activity context,Uri originalUri) throws IOException {
        String url;
        Bitmap bm = null;
        //外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口
        ContentResolver resolver = context.getContentResolver();
        bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);        //显得到bitmap图片
        //这里开始的第二部分，获取图片的路径：
        String[] proj = {MediaStore.Images.Media.DATA};
        //好像是android多媒体数据库的封装接口，具体的看Android文档
        Cursor cursor = context.managedQuery(originalUri, proj, null, null, null);
        //按我个人理解 这个是获得用户选择的图片的索引值
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        //将光标移至开头 ，这个很重要，不小心很容易引起越界
        cursor.moveToFirst();
        //最后根据索引值获取图片路径
        url = cursor.getString(column_index);
        return url;
    }

    public static  void openFile(File var0, Context var1) {
        try {
            Intent var2 = new Intent();
            var2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            var2.setAction(Intent.ACTION_VIEW);
            var2.addCategory(Intent.CATEGORY_DEFAULT);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Uri uriForFile = FileProvider.getUriForFile(var1, var1.getApplicationContext().getPackageName() + ".fileProvider", var0);
                var2.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                var2.setDataAndType(uriForFile, "application/vnd.android.package-archive");
            } else {
                var2.setDataAndType(Uri.fromFile(var0), "application/vnd.android.package-archive");
            }

            var1.startActivity(var2);
        } catch (Exception var5) {
            var5.printStackTrace();
            Toast.makeText(var1, "没有找到打开此类文件的程序", Toast.LENGTH_SHORT).show();
        }
    }

    public static String getMIMEType(File var0) {
        String var1 = "";
        String var2 = var0.getName();
        String var3 = var2.substring(var2.lastIndexOf(".") + 1, var2.length()).toLowerCase();
        var1 = MimeTypeMap.getSingleton().getMimeTypeFromExtension(var3);
        return var1;
    }
}